package com.araaya.eslimsmobile;

import java.util.List;
import java.util.StringTokenizer;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AnalogClock;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.LatLngBoundsCreator;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.maps.model.PolygonOptions;
/*import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection;*/

public class MyMapViewer extends FragmentActivity {

	//private MapView mapView;
	//private MapController mapController;
//	private GeoPoint geoPoint;
	private String coordinate;
	//private Projection projection;
	//private MyItemizedOverlay itemizedoverlay;

	private double array[][];

	private TextView txtSatelliteViewType;
	private TextView txtMapViewType;
	
	private GoogleMap mMap;
	
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map_view_new);
		setUpMapIfNeeded() ;
		txtMapViewType = (TextView) findViewById(R.id.txtMapViewType);
		txtSatelliteViewType = (TextView) findViewById(R.id.txtSatelliteViewType);
		
		txtMapViewType.setTextColor(Color.WHITE);
		txtSatelliteViewType.setTextColor(Color.BLACK);

		// click the map taye
		txtMapViewType.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				txtMapViewType.setTextColor(Color.WHITE);
				txtSatelliteViewType.setTextColor(Color.BLACK);
				mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
				
			}
		});

		// click the Satellite type
		txtSatelliteViewType.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				txtSatelliteViewType.setTextColor(Color.WHITE);
				txtMapViewType.setTextColor(Color.BLACK);
				mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

			}
		});
		
		final Button btnExitMap = (Button) findViewById(R.id.btnExitMap);

		// Close Map Button -- Close the map Map
		btnExitMap.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		//mapView = (MapView) findViewById(R.id.mapview);

		// get the coordinate value
		coordinate = getIntent().getExtras().getString("coordinate");
		
		

		// sets the zoom to see the location closer
		/*mapView.getController().setZoom(20);

		// this will let you to zoom in or out using the controllers
		mapView.setBuiltInZoomControls(true);
		// mapView.setSatellite(true);

		List<Overlay> mapOverlays = mapView.getOverlays();
		Drawable drawable = this.getResources().getDrawable(R.drawable.marker);
		projection = mapView.getProjection();

		itemizedoverlay = new MyItemizedOverlay(drawable, this);*/
        PolygonOptions polyOptions= new PolygonOptions();
        MarkerOptions mOptions = new MarkerOptions();
      		mOptions.flat(true);
      		mOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.markerblue));
      		
		if (setPoints(coordinate) != null) {
			polyOptions =setPoints(coordinate);
			polyOptions.strokeWidth(4);
			mMap.addPolygon(polyOptions);
			for(LatLng e : polyOptions.getPoints()){
				mMap.addMarker(mOptions.position(e));
			}
		}
	
		for (LatLng p: polyOptions.getPoints()) {
			Log.d("options: ", "polygon: lat: "+p.latitude+"lng: "+p.longitude);
			
		}

		CameraPosition position = new CameraPosition.Builder().target(polyOptions.getPoints().get(0))
				.zoom(20).build();
		mMap.animateCamera(CameraUpdateFactory.newCameraPosition(position));
	}

	


	
	private PolygonOptions setPoints(String values) {
		PolygonOptions p = null ;
		try {
			StringTokenizer stringTokenizer = new StringTokenizer(values);

			array = new double[stringTokenizer.countTokens()][3];
			int arrayCount = 0;
			double lat = 0;
			double lon = 0;
			float alt = 0;
			p = new PolygonOptions();
			while (stringTokenizer.hasMoreTokens()) {
				String firstToken = stringTokenizer.nextToken();

				StringTokenizer stringTokenizer2 = new StringTokenizer(
						firstToken, ",");

				while (stringTokenizer2.hasMoreTokens()) {
					int col = arrayCount % 3;
					int row = arrayCount / 3;

					String secondToken = stringTokenizer2.nextToken();
					array[row][col] = Double.parseDouble(secondToken);
					arrayCount++;

					if (col == 0) {
						lat = Double.parseDouble(secondToken);
					} else if (col == 1) {
						lon = Double.parseDouble(secondToken);
					} else if (col == 2) {
						alt = Float.parseFloat(secondToken);
					}

				}
				

				Log.d("lat==>", "lat==> " + lat);
				Log.d("lon==>", "lon==> " + lon);

				//GeoPoint point = new GeoPoint(lngVal, latVal);
			//	mapView.getController().setCenter(point);
			//	OverlayItem overlayitem = new OverlayItem(point, "", "");

			//	itemizedoverlay.addOverlay(overlayitem);

				p.add(new LatLng(lon, lat));
			}

		} catch (Exception e) {
			Log.d("Exception MyMap", e.getMessage());

		}

		return p;

	}

	// draw the line
	/*class MyOverlay extends Overlay {

		int latVal;
		int lngVal;

		public MyOverlay() {

		}*/

		/*public void draw(Canvas canvas, MapView mapv, boolean shadow) {
			super.draw(canvas, mapv, shadow);

			Paint mPaint = new Paint();
			mPaint.setDither(true);
			mPaint.setColor(Color.RED);
			mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
			mPaint.setStrokeJoin(Paint.Join.ROUND);
			mPaint.setStrokeCap(Paint.Cap.ROUND);
			mPaint.setStrokeWidth(2);

			for (int i = 0; i < array.length; i++) {
				latVal = (int) (array[i][0] * 1E6);
				lngVal = (int) (array[i][1] * 1E6);

				GeoPoint gP1 = new GeoPoint(lngVal, latVal);
				if (i == array.length - 1) {
					latVal = (int) (array[0][0] * 1E6);
					lngVal = (int) (array[0][1] * 1E6);
				} else {
					latVal = (int) (array[i + 1][0] * 1E6);
					lngVal = (int) (array[i + 1][1] * 1E6);
				}

				GeoPoint gP2 = new GeoPoint(lngVal, latVal);

				Point p1 = new Point();
				Point p2 = new Point();
				Path path = new Path();

				projection.toPixels(gP1, p1);
				projection.toPixels(gP2, p2);

				path.moveTo(p2.x, p2.y);
				path.lineTo(p1.x, p1.y);

				canvas.drawPath(path, mPaint);
				
			}

		}
*/
	
	 private void setUpMapIfNeeded() {
	        if (mMap != null) {
	            return;
	        }
	        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapFragment)).getMap();
	        if (mMap == null) {
	            return;
	        }
	    }

}
